package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by thoughtworker on 1/15/14.
 */

public class LibrarySystem {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    List<Book> bookList = new ArrayList<Book>();

    public void run() {
        welcome(System.out);
        makeBookList();
        printAvailableBooks(System.out);
        menu(System.out, reader);
    }


    public void welcome(PrintStream ps){
        ps.println("Welcome to Biblioteca!");
    }

    public void makeBookList(){
        bookList.add(new Book("Ender's Game", true));
    }

    public void makeBookList(List list){
        bookList = new ArrayList<Book>(list);
    }

    public void printAvailableBooks(PrintStream printStream){
        printStream.println("Available books:");
        printStream.println("");
        for(Book book: bookList){
            if(book.availability)
                printStream.println(book.getTitle());
        }

    }


    public void showListOfOptions(PrintStream printStream) {
        printStream.println("Enter 1 to List Books");
        printStream.println("Enter 2 to Check out a Book");
    }


    public String menu(PrintStream printStream, BufferedReader bufferedReader){
        showListOfOptions(printStream);
        String value = readUserInput(bufferedReader);
        if (!determineIfValidMenuInput(value))
            printStream.println("Select a valid option!");
        else if (Integer.parseInt(value)==1)
            printAvailableBooks(printStream);
        else
            checkout(printStream, bufferedReader);
        return value;
    }

    public String readUserInput(BufferedReader bufferedReader){
        String userinput = null;
        try {
            userinput = bufferedReader.readLine();
        } catch (IOException e) {
            System.out.println("Select a valid option!");
            e.printStackTrace();
        }
        return userinput;
    }

    public boolean determineIfValidMenuInput(String userinput){
        if (userinput.equals("1") || userinput.equals("2")) return true;
        return false;
    }

    public List<Book> getBookList() {
        return bookList;
    }

    public void checkout(PrintStream printStream, BufferedReader bufferedReader) {
        System.out.println("Please enter the title of the book you would like to check out!");
        printAvailableBooks(printStream);
        String title = readUserInput(bufferedReader);
        for (Book book: getBookList()){
            if (book.title.equals(title))
                book.availability = false;
        }
    }
}